import { cloudbaseApp, development } from '@/cloudbaseapi/cloudbase-api'
const db = cloudbaseApp().database()
const $ = db.command.aggregate
const _ = db.command
const { SGBDBNAME, SHIJIDB } = development()

/**
 * 获取诗集列表
 * @param limit
 * @param page
 * @param filterStr
 * @returns {Promise<GetRes>}
 */
export function getSgbItem(limit, page, filterStr = false) {
  const skip = (page - 1) * limit
  return new Promise(resolve => {
    db.collection(SGBDBNAME).count().then(count => {
      const total = count.total
      db.collection(SGBDBNAME).limit(limit).skip(skip).orderBy('shijiIndex', 'asc').orderBy('xuhao', 'desc').get().then(items => {
        items['total'] = total
        resolve(items)
      })
    })
  })
}

/**
 * 获取诗集类型
 * @returns {Promise<GetRes>}
 */
export function getShiJiType() {
  return db.collection(SHIJIDB).get()
}

/**
 * 通过id值查询诗集内容
 */
export function getShiJiItem(id) {
  return db.collection(SGBDBNAME).doc(id).get()
}
/**
 * 搜索接口
 * @param seacherVal {要搜索的字符串}
 * @returns {Promise<*>}
 */
export async function getFilterSgbItems(seacherVal = '',seacherShiJiType = -1) {
  let seacherWhere = {
    strIndexOf: _.gt(-1),
    shijiIndex: seacherShiJiType
  }
  if(seacherShiJiType == -1){
    delete seacherWhere['shijiIndex']
  }
  let fields = {_id: 1, xuhao: 1, isad: 1, isopern: 1, lyric: 1, mulu: 1, shijiIndex: 1, isupper:1,
    strIndexOf: $.indexOfCP(['$mulu', seacherVal])
  }
  const countData = await db.collection(SGBDBNAME).aggregate()
  .project(fields)
  .match(seacherWhere).count('total')
  .end()
  console.log(countData);
  if(countData.data.length==0){
    return { data: [], total: 0 }
  }
  let count = countData.data[0]['total']
  const filterItem = await db.collection(SGBDBNAME)
    .aggregate()
    .project(fields)
    .match(seacherWhere)
    .project({
      strIndexOf: 0
    })
    .limit(count)
    .end()
  const total = filterItem.data.length
  filterItem['total'] = total
  return filterItem
}
/**
 * 更新赞美条目
 * @param data
 */
export function updateSgbItem(data = {}, type) {
  const newData = { ...data }
  if (type === 'create') {
    newData['createDate'] = Date.now()
    newData['updateDate'] = Date.now()
  } else {
    newData['createDate'] = Date.now()
  }
  const id = newData['_id']
  delete newData['_id']
  delete newData['_openid']
  console.log(newData)
  return db.collection(SGBDBNAME).doc(id).set(newData)
}
/**
 * 控制诗集上下架
 */
export async function updateIsUpper(id, bool) {
  return db.collection(SGBDBNAME).where({ _id: id }).update({ isupper: bool})
}
